package com.twu.biblioteca;

import com.google.common.base.Optional;

import java.util.ArrayList;
import java.util.Collection;

public class Biblioteca {
    private Library<Book> books;
    private Library<Movie> movies;
    private Authenticator authenticator;
    private Optional<UserInformation> currentUser;

    public Biblioteca() {
        this(new ArrayList<Book>(), new ArrayList<Movie>(), new Authenticator(new ArrayList<User>()));
    }

    public Biblioteca(ArrayList<Book> books, ArrayList<Movie> movies, Authenticator authenticator) {
        this.books = new Library<Book>(books);
        this.movies = new Library<Movie>(movies);
        this.authenticator = authenticator;
        this.currentUser = Optional.absent();
    }

    public Collection<Book> getBooks() {
        return books.getAvailableItems();
    }

    public boolean checkoutBook(String title) {
        Book book = books.getItemByTitle(title);

        if (book == null) {
            return false;
        }

        return books.checkoutItem(book);
    }

    public boolean returnBook(String title) {
        Book book = books.getItemByTitle(title);

        if (book == null) {
            return false;
        }

        return books.returnItem(book);
    }

    public Collection<Movie> getMovies() {
        return movies.getAvailableItems();
    }

    public boolean checkoutMovie(String title) {
        Movie movie = movies.getItemByTitle(title);

        if (movie == null) {
            return false;
        }

        return movies.checkoutItem(movie);
    }

    public boolean login(LibraryNumber number, Password password) {
        Optional<User> user = authenticator.login(number, password);

        if (!user.isPresent()) {
            return false;
        }

        this.currentUser = Optional.of(user.get().getUserInformation());
        return true;
    }

    public Optional<UserInformation> getCurrentUserInformation() {
        return this.currentUser;
    }

    public boolean isLoggedIn() {
        return currentUser.isPresent();
    }
}
